package ucenter

import (
	"log"
	global "yundata-service/internal"
	um "yundata-service/pkg/model/ucenter"

	"github.com/dgrijalva/jwt-go"
	"gorm.io/gorm"
)

type UserAction struct {
	global.ActionModel
}

// 获取用户详情
func (ac *UserAction) GetUser() {

	c := ac.Ctx
	currentUser := c.MustGet("user").(jwt.MapClaims)

	user := &um.User{}

	db := global.GDb
	tx := db.Session(&gorm.Session{PrepareStmt: true})
	log.Println(currentUser)

	where := "`id` = ?"
	tx.Model(user).Where(where, currentUser["id"])
	tx.Find(user)

	type Data struct {
		Us um.User `json:"user"`
	}
	resData := Data{*user}

	ac.Success("获取数据成功", resData)
}

// 获取用户列表
func (ac *UserAction) GetUserList() {
	db := global.GDb
	// db.AutoMigrate(&User{}, &dpt.Dpt{})

	var users []um.User
	var UserItems []um.UserItem

	// db.Preload("Dpt").Limit(10).Find(&users)
	db.Limit(10).Find(&users)
	// GetSexAttr
	for _, user := range users {
		userItem := um.UserItem{User: user, SexAttr: user.GetSexAttr(), DptAttr: user.GetDpt()}
		UserItems = append(UserItems, userItem)
	}

	type Data struct {
		Users []um.UserItem `json:"users"`
	}
	data := &Data{Users: UserItems}

	ac.Success("获取数据成功", data)
}

// create func update user with gin
func (ac *UserAction) UpdateUser() {

	db := global.GDb
	userModel := &um.User{}

	c := ac.Ctx
	if err := c.ShouldBindJSON(userModel); err != nil {
		ac.Fail("参数错误")
		return
	}

	if err := db.Model(userModel).Updates(userModel).Error; err != nil {
		ac.Fail("更新失败")
		return
	}

	ac.Success("更新成功")
}

// 删除用户
func (ac *UserAction) DeleteUser() {
	db := global.GDb
	userModel := &um.User{}

	c := ac.Ctx
	if err := c.ShouldBindJSON(userModel); err != nil {
		ac.Fail("参数错误")
		return
	}

	if err := db.Delete(userModel).Error; err != nil {
		ac.Fail("删除失败")
		return
	}

	ac.Success("删除成功")
}
